<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 客户管理
 */
declare (strict_types=1);

namespace app\backend\controller;

use app\backend\base\controller\Base;
use app\backend\validate\UserValidate;
use app\extend\model\Reduce;
use think\facade\Db;

class User extends Base
{
    /**
     * 列表
     */
    public function index()
    {
        if(request()->isPost()){
            $validate = new UserValidate();
            $ret = $validate->scene('index')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $page = input('page/d',1);
            $limit = input('limit/d',20);
            $fieldName = input('field_name','');
            $fieldValue = input('field_value','');
            $levelId = input('level_id/d','');
            $dateType = input('date_type','created_at');
            $startDate = input('start_date','');
            $endDate = input('end_date','');

            $where = [
                ['is_delete','=',0],
                [$dateType,'between',[$startDate,$endDate]]
            ];
            //字段筛选
            if (!empty($fieldName) && !empty($fieldValue)){
                switch($fieldName){
                    case 'account'://账号
                        $where[] = ['account','=',$fieldValue];
                        break;
                    case 'mobile'://手机号码
                        $where[] = ['mobile','=',$fieldValue];
                        break;
                    case 'id'://用户ID
                        $where[] = ['id','=',$fieldValue];
                        break;
                }
            }

            //会员等级
            if (is_numeric($levelId)) {
                $where[] = ['level_id', '=', $levelId];
            }

            $list = [];
            $count = \app\extend\model\User::where($where)->count();
            if($count > 0){
                $list = \app\extend\model\User::where($where)->append(['level_name_txt'])->order(['id' => 'desc'])->page($page)->limit($limit)->select();
            }

            return json([
                'code' => 0,
                'msg' => '获取成功',
                'count' => $count,
                'data' => $list,
            ])->send();
        } else {
            $levelList = \app\extend\model\Level::field('id,level_name')->order(['id'=>'asc'])->select();

            return view('index', [
                'level_list' => $levelList
            ]);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if(request()->isPost()){
            $validate = new UserValidate();
            $ret = $validate->scene('add')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $account = input('account','');
            $mobile = input('mobile','');
            $password = input('password','');
            $payPassword = input('pay_password','');
            $levelId = input('level_id/d',1);
            $status = input('status/d',0);

            $userInfo = \app\extend\model\User::where([
                ['account','=',$account]
            ])->field('id')->find();
            if(!empty($userInfo)){
                return json(_E('账号已经存在'));
            }

            $pwdArr = password($password);
            $payPwdArr = password($payPassword);

            $result = \app\extend\model\User::insert([
                'account' => $account,
                'mobile' => $mobile,
                'password' => $pwdArr['password'],
                'salt' => $pwdArr['salt'],
                'pay_password' => $payPwdArr['password'],
                'pay_salt' => $payPwdArr['salt'],
                'level_id' => $levelId,
                'status' => $status,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if(!$result){
                return json(_E('添加失败'));
            } else {
                return json(_S('添加成功'));
            }
        }
    }

    /**
     * 修改
     */
    public function edit()
    {
        if(request()->isPost()){
            $validate = new UserValidate();
            $ret = $validate->scene('edit')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id',0);
            $mobile = input('mobile','');
            $password = input('password','');
            $payPassword = input('pay_password','');
            $levelId = input('level_id/d',1);
            $status = input('status/d',0);

            $saveData = [
                'mobile' => $mobile,
                'level_id' => $levelId,
                'status' => $status,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if(!empty($password)){
                $pwdArr = password($password);
                $saveData['password'] = $pwdArr['password'];
                $saveData['salt'] = $pwdArr['salt'];
            }

            if(!empty($payPassword)){
                $pwdArr = password($payPassword);
                $saveData['pay_password'] = $pwdArr['password'];
                $saveData['pay_salt'] = $pwdArr['salt'];
            }

            $result = \app\extend\model\User::where([
                ['id','=',$id]
            ])->update($saveData);

            if(!$result){
                return json(_E('修改失败'));
            } else {
                return json(_S('修改成功'));
            }
        }
    }

    /**
     * 充值
     */
    public function recharge()
    {
        if(request()->isPost()){
            $validate = new UserValidate();
            $ret = $validate->scene('recharge')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id',0);
            $money = input('money','');

            $userInfo = \app\extend\model\User::where([
                ['id','=',$id]
            ])->field('balance')->find();

            try {
                // 启动事务
                Db::startTrans();

                \app\extend\model\User::where([
                    ['id','=',$id]
                ])->update([
                    'balance' => $userInfo->balance + $money,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                \app\extend\model\Recharge::insert([
                    'uid' => $id,
                    'money' => $money,
                    'balance' => $userInfo->balance + $money,
                    'remark' => '系统充值',
                    'operater' => session('nickname'),
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                Db::commit();
                return json(_S('充值成功'));
            } catch (\Exception $e){
                Db::rollback();
                return json(_E('充值失败,错误:'.$e->getMessage()));
            }
        }
    }

    /**
     * 减款
     */
    public function reduce()
    {
        if(request()->isPost()){
            $validate = new UserValidate();
            $ret = $validate->scene('reduce')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id',0);
            $money = input('money','');

            $userInfo = \app\extend\model\User::where([
                ['id','=',$id]
            ])->field('balance')->find();

            if($userInfo->balance < $money){
                return json(_E('减款金额大于用户余额'));
            }

            try {
                // 启动事务
                Db::startTrans();

                \app\extend\model\User::where([
                    ['id','=',$id]
                ])->update([
                    'balance' => $userInfo->balance - $money,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                Reduce::insert([
                    'uid' => $id,
                    'money' => $money,
                    'balance' => $userInfo->balance - $money,
                    'remark' => '系统扣款',
                    'operater' => session('nickname'),
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                Db::commit();
                return json(_S('减款成功'));
            } catch (\Exception $e){
                Db::rollback();
                return json(_E('减款失败,错误:'.$e->getMessage()));
            }
        }
    }

    /**
     * 冻结、解冻账户
     */
    public function editStatus()
    {
        if(request()->isPost()){
            $validate = new UserValidate();
            $ret = $validate->scene('editStatus')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id',0);
            $status = input('status/d',0);

            $result = \app\extend\model\User::where([
                ['id','=',$id]
            ])->update([
                'status' => $status,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if(!$result){
                return json(_E('修改失败'));
            } else {
                return json(_S('修改成功'));
            }
        }
    }

    /**
     * 修改日息宝金额
     */
    public function editRixibaoMoney()
    {
        if(request()->isPost()){
            $validate = new UserValidate();
            $ret = $validate->scene('editRixibaoMoney')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id',0);
            $money = input('money','');

            $result = \app\extend\model\User::where([
                ['id','=',$id]
            ])->update([
                'rixibao_money' => $money,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if(!$result){
                return json(_E('修改失败'));
            } else {
                return json(_S('修改成功'));
            }
        }
    }

    /**
     * 修改银行卡
     */
    public function editBankCard()
    {
        $id = input('id/d', 0);

        if (request()->isPost()) {
            $validate = new UserValidate();
            $ret = $validate->scene('editBankCard')->check(input());
            if (!$ret) {
                return json(_E($validate->getError()));
            }

            $username = input('username', '');
            $number = input('number', '');
            $bankName = input('bank_name', '');
            $bankBranchName = input('bank_branch_name', '');

            $result = \app\extend\model\BankCard::where([
                ['id', '=', $id]
            ])->update([
                'username' => $username,
                'number' => $number,
                'bank_name' => $bankName,
                'bank_branch_name' => $bankBranchName,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if (!$result) {
                return json(_E('修改失败'));
            } else {
                return json(_S('修改成功'));
            }

        } else {
            $bankCardInfo = \app\extend\model\BankCard::where([
                ['uid','=',$id]
            ])->find();

            if(empty($bankCardInfo)){
                return json(_E('该用户未绑银行卡'));
            }

            return json(_S('获取成功',$bankCardInfo));
        }
    }

    /**
     * 删除银行卡
     */
    public function delBankCard()
    {
        if (request()->isPost()) {
            $validate = new UserValidate();
            $ret = $validate->scene('delBankCard')->check(input());
            if (!$ret) {
                return json(_E($validate->getError()));
            }
            $id = input('id/d', 0);

            $bankCardInfo = \app\extend\model\BankCard::where([
                ['uid', '=', $id]
            ])->field('id')->find();
            if(empty($bankCardInfo)){
                return json(_E('该用户未绑银行卡'));
            }

            $result = \app\extend\model\BankCard::where([
                ['id', '=', $id]
            ])->delete();
            if (!$result) {
                return json(_E('删除失败'));
            } else {
                return json(_S('删除成功'));
            }
        }
    }

    /**
     * 添加用户实名认证
     */
    public function addUserAuth()
    {
        $id = input('id/d', 0);
        if (request()->isPost()) {
            $validate = new UserValidate();
            $ret = $validate->scene('addUserAuth')->check(input());
            if (!$ret) {
                return json(_E($validate->getError()));
            }

            $realName = input('real_name', '');
            $idCard = input('id_card', '');

            $userAuthInfo = \app\extend\model\UserAuth::where([
                ['uid', '=', $id]
            ])->field('id')->find();
            if(!empty($userAuthInfo)){
                return json(_E('该用户已经提交实名认证资料'));
            }

            $result = \app\extend\model\UserAuth::insert([
                'uid' => $id,
                'real_name' => $realName,
                'id_card' => $idCard,
                'status' => 1,
                'operater' => session('nickname'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if (!$result) {
                return json(_E('添加失败'));
            } else {
                return json(_S('添加成功'));
            }
        } else {
            $userAuthInfo = \app\extend\model\UserAuth::where([
                ['uid', '=', $id]
            ])->field('id')->find();

            if(!empty($userAuthInfo)){
                return json(_E('该用户已经提交实名认证资料'));
            }

            return json(_S('没有实名认证'));
        }
    }

    /**
     * 删除
     */
    public function del()
    {
        if(request()->isPost()){
            $validate = new UserValidate();
            $ret = $validate->scene('del')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id',0);

            try {
                // 启动事务
                Db::startTrans();

                \app\extend\model\User::where([
                    ['id','=',$id]
                ])->update([
                    'is_delete' => 1,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                Db::commit();
                return json(_S('删除成功'));
            } catch (\Exception $e){
                Db::rollback();
                return json(_E('删除失败,错误:'.$e->getMessage()));
            }
        }
    }
}
